//
//  XMN_GroupTopViewController.m
//  B段项目
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "XMN_GroupTopViewController.h"
#import "XMN_GroupList.h"
#import "XMN_GroupListCell.h"
#import "XMN_PostsViewController.h"
#import "XMN_GroupDetailViewController.h"

@interface XMN_GroupTopViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSourceArray;
@property(nonatomic, strong)NSDictionary *topDic;
@property(nonatomic, strong)myView *headerView;
@property(nonatomic, strong)UIImageView *headerImageView;
@property(nonatomic, strong)UIButton *infoButton;
@property(nonatomic, strong)UILabel *numLabel;
@property(nonatomic, strong)UILabel *talklabel;
@property(nonatomic, assign)NSInteger start;

@property(nonatomic, strong)XMN_ProgressHUD *HUD;
@end

@implementation XMN_GroupTopViewController

-(void)loadView{
    [super loadView];
    
    //初始化
    _dataSourceArray = [NSMutableArray array];
    _topDic = [NSDictionary dictionary];
    //数据请求
//    [self getFirstDataByURLString];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView NightWithType:UIViewColorType2];
    [self.view addSubview:_tableView];
    
    _headerView = [[myView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 150 * FitHeight)];
    [self createHeaderView];
    _tableView.tableHeaderView = _headerView;
    
    
//    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        if (_dataSourceArray.count != 0) {
//            [_dataSourceArray removeAllObjects];
//        }
//        [self getFirstDataByURLString];
//    }];
//    
//    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _start++;
//        [self getBeforeDataByURLString];
//    }];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(getFirstDataByURLString)];
    _tableView.header = header;
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 1; i <= 9; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lda", i]];
        [array addObject:image];
    }
    [header setImages:array duration:1 forState:MJRefreshStatePulling];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(getBeforeDataByURLString)];
    _tableView.footer = footer;
    [footer setImages:array duration:1 forState:MJRefreshStateRefreshing];
    [_tableView.header beginRefreshing];

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _group.title;
    
    _HUD = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _HUD.XMN_label.text = @"Waiting...";
    [self.view addSubview:_HUD];
    // Do any additional setup after loading the view.
}

-(void)createHeaderView{
    _headerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 120 * FitHeight)];
    [_headerView addSubview:_headerImageView];
    
    _numLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 * FitWidth, 130 * FitHeight, 120 * FitWidth, 10 * FitHeight)];
    _numLabel.font = [UIFont systemFontOfSize:10];
    _numLabel.textColor = [UIColor lightGrayColor];
    [_headerView addSubview:_numLabel];
    
    _talklabel = [[UILabel alloc]initWithFrame:CGRectMake(150 * FitWidth, _numLabel.frame.origin.y, 120 * FitWidth, _numLabel.frame.size.height)];
    _talklabel.font = [UIFont systemFontOfSize:10];
    _talklabel.textColor = [UIColor lightGrayColor];
    [_headerView addSubview:_talklabel];
    
    _infoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _infoButton.frame = CGRectMake(ScreenWidth - 70 * FitWidth, 125 * FitHeight, 50 * FitWidth, 20 *FitHeight);
    _infoButton.layer.masksToBounds = YES;
    _infoButton.layer.cornerRadius = 10;
    _infoButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [_infoButton setTitle:@"详情" forState:UIControlStateNormal];
    _infoButton.backgroundColor = [UIColor colorWithRed:1 green:0.69 blue:0.66 alpha:1];
    [_infoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_infoButton addTarget:self action:@selector(infoButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:_infoButton];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 149 * FitHeight, ScreenWidth, 1 * FitHeight)];
    label.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    [_headerView addSubview:label];
}

#pragma mark - tableView相关设置
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSourceArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    XMN_GroupListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[XMN_GroupListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_dataSourceArray.count == 0) {
        return cell;
    }
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:[_topDic objectForKey:@"bannerimg"]]];
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:[_topDic objectForKey:@"bannerimg"]] placeholderImage:[UIImage imageNamed:@"占位图"]];
    _numLabel.text = [NSString stringWithFormat:@"成员: %@", [_topDic objectForKey:@"membernum"]];
    _talklabel.text = [NSString stringWithFormat:@"话题: %@", [_topDic objectForKey:@"postsnum"]];
    cell.groupList = [_dataSourceArray objectAtIndex:indexPath.row];
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140 * FitHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    XMN_PostsViewController *postsVC = [[XMN_PostsViewController alloc]init];
    [self.navigationController pushViewController:postsVC animated:YES];
    postsVC.idString = [[_dataSourceArray objectAtIndex:indexPath.row] contentid];
    postsVC.titleString = [[_dataSourceArray objectAtIndex:indexPath.row] title];
    postsVC.contentString = [[_dataSourceArray objectAtIndex:indexPath.row] content];
}

#pragma mark - 数据请求
-(void)getFirstDataByURLString{
    if ([_tableView.header isRefreshing]) {
                if (_dataSourceArray.count != 0) {
                    [_dataSourceArray removeAllObjects];
                }
        _start = 0;

        
    }
    [HTTPMethod getDataByString:@"http://api2.pianke.me/group/group_info" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"groupid=%@&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg", _group.groupid]] WithDataBlock:^(id data) {
//        NSLog(@"%@", data);
        _topDic = [[data objectForKey:@"data"] objectForKey:@"groupinfo"];
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"postslist"];
        for (NSDictionary *dic in array) {
            XMN_GroupList *groupList = [[XMN_GroupList alloc]init];
            [groupList setValuesForKeysWithDictionary:dic];
            [_dataSourceArray addObject:groupList];
        }
//        NSLog(@"%ld", _dataSourceArray.count);
        [_tableView.header endRefreshing];
        [_tableView reloadData];
        [_HUD removeFromSuperview];
    }];
}

-(void)getBeforeDataByURLString{
    _start ++;
    [HTTPMethod getDataByString:@"http://api2.pianke.me/group/posts_list" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"start=%ld&groupid=%@&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg&limit=10", _start * 10, _group.groupid]] WithDataBlock:^(id data) {
//        NSLog(@"%@", data);
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"postslist"];
        for (NSDictionary *dic in array) {
            XMN_GroupList *groupList = [[XMN_GroupList alloc]init];
            [groupList setValuesForKeysWithDictionary:dic];
            [_dataSourceArray addObject:groupList];
        }
//        NSLog(@"=====------%ld", _dataSourceArray.count);
        [_tableView.footer endRefreshing];
        [_tableView reloadData];
    }];
}

#pragma mark - button触发事件
-(void)infoButtonAction{
    XMN_GroupDetailViewController *groupDetailVC = [[XMN_GroupDetailViewController alloc]init];
    [self.navigationController pushViewController:groupDetailVC animated:YES];
    groupDetailVC.group = _group;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
